import {createSlice,PayloadAction,createAsyncThunk} from '@reduxjs/toolkit'
import axios from 'axios'
interface SearchState{
    isloading:boolean,
    error:null|string,
    productlist:any[],
    pagination:any
}
const initialState:SearchState={
    isloading:true,
    error:null,
    productlist:[],
    pagination:null
}
interface paramtype{
    pagenum:number,
    pagesize:number,
    keywords:number
}
export const searchProductList=createAsyncThunk(
    "productList/searchProductList",
    async (theparams:{pagenumber:string|number,pagesize:string|number,keyword:string|undefined})=>{
        var params=`?pagenumber=${theparams.pagenumber}&pagesize=${theparams.pagesize}`;
        if(theparams.keyword!==undefined){
            params+=`&keyword=${theparams.keyword}`;
        }
        const response=await axios.get('http://123.56.149.216:8080/api/touristRoutes'+params,{
            headers: {"x-icode": "69ACF3816BF5D32D"}
        })

        return {
            productlist:response.data,
            pagination:JSON.parse(response.headers["x-pagination"])
        }
    }
)
export const productlistSlice=createSlice({
    name:"productList",
    initialState,
    reducers:{},
    extraReducers:{
        [searchProductList.pending.type]:(state)=>{
            state.isloading=true;
        },
        [searchProductList.fulfilled.type]:(state,action)=>{
            state.isloading=false;
            state.productlist=action.payload.productlist;
            state.pagination=action.payload.pagination;
        },
        [searchProductList.rejected.type]:(state,action)=>{
            state.isloading=false;
            state.error=action.error.message;
        }
    }
})